/*
 * Copyright kecp
 * Jun 02, 2010
 */

package Gui;

import LBS.Location;
import Tool.Debugger;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import traveller.Assistant;

/**
 * 用于搜索和管理地址
 * @author kecp
 */
public class AddressSearch implements CommandListener ,ItemCommandListener{

    private MIDlet midlet;
    Thread searchThread = null;
    Assistant assist = Assistant.getTheAssistant();
    StringItem itemGroup[] = new StringItem[10];
  //  TextField itemGroup[] = new TextField[10];
    List list;
    Vector locts;
    private Command itemCmd;
    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Form addressForm;
    private TextField searchField;
    private StringItem searchResult;
    private Command backCommand;
    private Command searchCmd;
    //</editor-fold>//GEN-END:|fields|0|


    /**
     * The AddressSearch constructor.
     * @param midlet the midlet used for getting
     */
    public AddressSearch (MIDlet midlet) {
         this.midlet = midlet;
         itemCmd = new Command("结果",Command.ITEM,5);
         getAddressForm().setCommandListener(this);
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|2-switchDisplayable|0|2-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|2-switchDisplayable|0|2-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|2-switchDisplayable|1|2-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|2-switchDisplayable|1|2-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|2-switchDisplayable|2|
    //</editor-fold>//GEN-END:|2-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: addressForm ">//GEN-BEGIN:|11-getter|0|11-preInit
    /**
     * Returns an initiliazed instance of addressForm component.
     * @return the initialized component instance
     */
    public Form getAddressForm() {
        if (addressForm == null) {//GEN-END:|11-getter|0|11-preInit
            // write pre-init user code here
            addressForm = new Form("\u641C\u7D22\u5730\u5740", new Item[] { getSearchField(), getSearchResult() });//GEN-BEGIN:|11-getter|1|11-postInit
            addressForm.addCommand(getBackCommand());
            addressForm.addCommand(getSearchCmd());
            addressForm.setCommandListener(this);//GEN-END:|11-getter|1|11-postInit

            // write post-init user code here
        }//GEN-BEGIN:|11-getter|2|
        return addressForm;
    }
    //</editor-fold>//GEN-END:|11-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: searchField ">//GEN-BEGIN:|12-getter|0|12-preInit
    /**
     * Returns an initiliazed instance of searchField component.
     * @return the initialized component instance
     */
    public TextField getSearchField() {
        if (searchField == null) {//GEN-END:|12-getter|0|12-preInit
            // write pre-init user code here
            searchField = new TextField("\u641C\u7D22", null, 32, TextField.ANY);//GEN-LINE:|12-getter|1|12-postInit
            // write post-init user code here
        }//GEN-BEGIN:|12-getter|2|
        return searchField;
    }
    //</editor-fold>//GEN-END:|12-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|4-commandAction|0|4-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|4-commandAction|0|4-preCommandAction
        // write pre-action user code here
        if (displayable == addressForm) {//GEN-BEGIN:|4-commandAction|1|14-preAction
            if (command == backCommand) {//GEN-END:|4-commandAction|1|14-preAction
                // write pre-action user code here
                ((MainMIDlet)midlet).back();
//GEN-LINE:|4-commandAction|2|14-postAction
                // write post-action user code here
            } else if (command == searchCmd) {//GEN-LINE:|4-commandAction|3|16-preAction
                // write pre-action user code here
                procSearch();
//GEN-LINE:|4-commandAction|4|16-postAction
                // write post-action user code here
            }//GEN-BEGIN:|4-commandAction|5|4-postCommandAction
        }//GEN-END:|4-commandAction|5|4-postCommandAction

       
    }//GEN-BEGIN:|4-commandAction|6|
    //</editor-fold>//GEN-END:|4-commandAction|6|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|13-getter|0|13-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|13-getter|0|13-preInit
            // write pre-init user code here
            backCommand = new Command("\u540E\u9000", Command.BACK, 0);//GEN-LINE:|13-getter|1|13-postInit
            // write post-init user code here
        }//GEN-BEGIN:|13-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|13-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: searchCmd ">//GEN-BEGIN:|15-getter|0|15-preInit
    /**
     * Returns an initiliazed instance of searchCmd component.
     * @return the initialized component instance
     */
    public Command getSearchCmd() {
        if (searchCmd == null) {//GEN-END:|15-getter|0|15-preInit
            // write pre-init user code here
            searchCmd = new Command("\u786E\u5B9A", Command.ITEM, 0);//GEN-LINE:|15-getter|1|15-postInit
            // write post-init user code here
        }//GEN-BEGIN:|15-getter|2|
        return searchCmd;
    }
    //</editor-fold>//GEN-END:|15-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: searchResult ">//GEN-BEGIN:|17-getter|0|17-preInit
    /**
     * Returns an initiliazed instance of searchResult component.
     * @return the initialized component instance
     */
    public StringItem getSearchResult() {
        if (searchResult == null) {//GEN-END:|17-getter|0|17-preInit
            // write pre-init user code here
            searchResult = new StringItem("\u641C\u7D22\u7ED3\u679C", "");//GEN-LINE:|17-getter|1|17-postInit
            // write post-init user code here
        }//GEN-BEGIN:|17-getter|2|
        return searchResult;
    }
    //</editor-fold>//GEN-END:|17-getter|2|



    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(midlet);
    }

    /**
     * Exits MIDlet.
     * Note you have to implement proper MIDlet destroying.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        // midlet.destroyApp(true);
        midlet.notifyDestroyed();
    }


    /**
     * 执行搜索，会有阻塞
     */
      void procSearch() {

        if( searchThread == null ) {
            try {
             searchThread = ( new Thread() {
                    public void run() {
                        Location loct;
                        while( true ) {
                                synchronized (this) {
                                    StringBuffer sb = new StringBuffer("");
                                    //搜索更新地址
                                   locts = assist.searchAddress(getSearchField().getString());
                                    //显示结果
                                    updateItemGroup();
                                    try {
                                        this.wait();
                                    } catch (InterruptedException ex) {
                                        ex.printStackTrace();
                                    }
                            }
                        }

                    }
                });
                searchThread.start();
            }
            catch( Exception exc ){
                exc.printStackTrace();
            }

        }
        synchronized(searchThread ) {
            searchThread.notifyAll();
        }

    }
      
      
    /**
     * 将搜索到的结果显示出来
     */
    void updateItemGroup(){
        short i;
        Location loct;
        Enumeration enums = locts.elements();
        Form form = getAddressForm();
        //先清空
        while( form.size() > 2 ) {
            form.delete(2);
        }

        //添加
        for( i=0;i<itemGroup.length && enums.hasMoreElements() ;i++) {

            loct = (Location) enums.nextElement();
            if( itemGroup[i] == null ) {

                  itemGroup[i] = new StringItem("", loct.getName(), Item.HYPERLINK);
                  //必须设置默认命令才能获得输入焦点
                  itemGroup[i].setDefaultCommand(itemCmd);
                  itemGroup[i].setItemCommandListener(this);
                  itemGroup[i].setLayout(Item.LAYOUT_LEFT );
            }
           itemGroup[i].setText(loct.getName());
           //  itemGroup[i].setString(loct.getName());
            form.append(itemGroup[i]);
        }
    }

    void selectedAddress( Item item ) {
        short i;
        Location loct;

        for( i=0;i < itemGroup.length; i++ ) {
            if( itemGroup[i] == item )
                break;
        }
        loct = (Location) locts.elementAt(i);
        Debugger.addDebugInfo("selected dest:" + loct.getName());
        assist.setDestLocation( loct );
    }

    public void commandAction(Command c, Item item) {
         if( c == itemCmd ) {
             selectedAddress( item );
         }

    }

}
